<?php

/**
 * User: luchao
 * Createtime: 2016/10/20 16:03
 * desc：争议
 */
namespace AuctionCore\Dispute;

use AuctionCore\CarResource\CarModel;
use AuctionCore\System\AuctionException;
use AuctionCore\CarOwner\Owner;
use AuctionCore\CarDealer\Dealer;
use AuctionCore\AuctionOrder\AuOrder;
use AuctionCore\ChangeOrder\ChangeOrder;
use AuctionCore\CarDealer\AssetCenter;
use AuctionCore\CarResource\BreachCar;
use AuctionCore\CarResource\SelfReceiveCar;
use AuctionCore\PurchaseOrder\PurchaseOrder;
use AuctionCore\Cashier\Payment;
use AuctionCore\Other\Address;
use AuctionCore\Cashier\Collection;
use AuctionCore\CarResource\Car;
use AuctionCore\AuctionOrder\Signature;
use AuctionCore\Fours\Fours;
use AuctionCore\CarResource\CarSource;
use AuctionCore\AuctionOrder\Transfer;
use AuctionBack\Logic\CarReportLogic;

class Dispute
{
    const STATUS_HANDLE = 1; // 待审核
    const STATUS_ADOPT = 2; // 已通过
    const STATUS_REJECT = 3; // 驳回

    const CUSTOMER_DEALER = 1; //车商
    const CUSTOMER_OWNER = 2; //车主

    protected $did = null;

    public function __construct($did)
    {
        $this->did = $did;
    }

    /**
     * 添加争议记录
     * @param  array $data
     * @return   boolean
     */
    public static function DisputeAdd($data = array())
    {
        //事务开始
        M()->startTrans();
        $time = date('Y-m-d H:i:s');
        // 记录争议处理结果
        $params = array(
            'order_id' => $data['order_id'],
            'order_no' => $data['order_no'],
            'po_id' => $data['po_id'],
            'po_no' => $data['po_no'],
            'car_plate_number' => $data['car_plate_number'],
            'order_status' =>$data['order_status'],
            'od_id' => $data['od_id'],
            'od_type' => $data['od_type'],
            'remark' => $data['remark'],
            'dispute_reason' => $data['dispute_reason'],
            'status' => 1,
            'createtime' => $time
        );
        $res_dispute = M('dispute')->add($params);
        //更新拍单争议状态
        $o = new AuOrder($data['order_id']);
        //锁定拍单 采购单 收付款单
        $res_lock = self::lockAll($data);

        if ($data['od_type'] == self::CUSTOMER_DEALER){
            $customer = "dealer_id";
            $res_o = $o->update(['dealer_issue_status'=>1,'is_dealer_issue'=>1]);
        }
        elseif ($data['od_type'] == self::CUSTOMER_OWNER){
            $customer = "owner_id";
            $res_o = $o->update(['is_dealer_issue'=>1]);
        }
        if ($res_dispute && $res_o && $res_lock) {
            //事务提交
            M()->commit();
            // //记录操作日志
            // $log = array('order_id' => $data['order_id'], $customer => $data['od_id'], 'action' => '产生争议');
            // \AuctionCore\System\SystemLog::add($log);
            return true;
        } else {
            M()->rollback();
            \Think\Log::record('添加争议时发生回滚事件！order_id:' . $data['order_id'] . ',' . $customer . ':' . $data['od_id']);
            return false;
        }
    }

    public static function getOneInfo($did){
        return M('dispute')->where(['did' =>$did])->find();
    }
    
    public function detail()
    {
        return M('dispute')->where(['did' => $this->did])->find();
    }

    public function update($data)
    {
        return M('dispute')->where(['did' => $this->did])->save($data);
    }

    //找到上一条争议信息
    public static function LastDisputedetail($data){
        $prefix = C('DB_PREFIX');
        $map  = [];
        $map['ml.sid'] = ['eq',$data['sid']];
        $map['d.did'] = ['neq',$data['did']];
        $map['ml.status'] = ['neq',4];
        $map['ml.modify_result'] = ['eq',1];
        if ($data['is_dealer'] == 1) {
            $map['ml.source'] = ['lt',8];
        }else{
            $map['ml.source'] = ['gt',7];
        }
        $res = M('dispute')->alias('d')->field("d.*,ml.mid,ml.modify_no,ml.modify_reason,ml.modify_result,ml.modify_desc,ml.dealer_compensate,ml.owner_compensate,ml.status as modify_status,ml.createtime as modify_createtime")
            ->join($prefix . "modify_list as ml ON ml.did = d.did")
            ->where($map)->order('d.did desc')->find();
        return $res;
    }

    /**
     * 争议列表
     * @return   array
     */
    public static function DisputeList($page = 1, $size = 10, $params)
    {
        $page = (int)$page < 1 ? 1 : (int)$page;
        $size = (int)$size < 1 ? 10 : (int)$size;
        $order = "";
        $prefix = C('DB_PREFIX');
        $map = array();
        if ($params['status'] == 1) {
            $map[] = array('d.status' => 1);
            $order = "d.createtime desc";
        } elseif ($params['status'] == 2) {
            $map[] = array('d.status' => 2);
            $order = "d.audittime desc";
        } elseif ($params['status'] == 3) {
            $map[] = array('d.status' => 3);
            $order = "d.audittime desc";
        }elseif ($params['status'] == 4) {
            $map[] = array('d.status' => 4);
            $order = "d.canceltime desc";
        }
        if (!empty($params['search_key'])) {
            $where['o.order_no'] = array('like', $params['search_key'] . "%");
            $where['c.sno'] = array('like', $params['search_key'] . "%");
            $where['_logic'] = 'or';
            $map['_complex'] = $where;
        }
        if ($params['seller_buyer']) {
            $map['d.od_type'] = $params['seller_buyer'];
        }
        if ($params['car_plate_number']) {
            $map['d.car_plate_number'] = array('like', $params['car_plate_number'] . "%");
        }
        if (!empty($params['location_area'])) {
            $map['c.location_area'] = array('in', $params['location_area']);
        }
        $cols = "d.*,ml.modify_no,c.car_id,c.brand_id,c.location_area,c.series_id,c.model_id,c.sno,c.car_no,e.real_name,cd.contact_person,co.seller_name";

        $total = M('dispute')->alias('d')
            ->join($prefix . "order as o ON o.order_id = d.order_id")
            ->join($prefix . "cars as c ON c.car_id = o.car_id")
            ->join('LEFT JOIN ' . $prefix . "car_owner as co ON co.owner_id=c.owner_id")
            ->join('LEFT JOIN ' . $prefix . "employee as e ON e.emp_id=co.checker_id")
            ->join('LEFT JOIN ' . $prefix . "modify_list as ml ON ml.did = d.did ")
            ->join('LEFT JOIN ' . $prefix . "car_dealer as cd ON cd.dealer_id = d.od_id")
            ->where($map)->count();
        $list = M('dispute')->alias('d')->field($cols)
            ->join($prefix . "order as o ON o.order_id = d.order_id")
            ->join($prefix . "cars as c ON c.car_id = o.car_id")
            ->join('LEFT JOIN ' . $prefix . "car_owner as co ON co.owner_id=c.owner_id")
            ->join('LEFT JOIN ' . $prefix . "employee as e ON e.emp_id=co.checker_id")
            ->join('LEFT JOIN ' . $prefix . "modify_list as ml ON ml.did = d.did ")
            ->join('LEFT JOIN ' . $prefix . "car_dealer as cd ON cd.dealer_id = d.od_id")
            ->where($map)->limit($size)->page($page)->order($order)->select();
        // echo M()->getlastsql();
        $cm = new CarModel();
        $addr = new Address();
        //数据处理
        if (!empty($list)) {
            foreach ($list as $key => $val) {
                $list[$key] = $val;
                $brand = $cm->get_model_by_id($val['brand_id'], 'brand');
                $series = $cm->get_model_by_id($val['series_id'], 'series');
                $model = $cm->get_model_by_id($val['model_id']);
                $list[$key]['model'] = $brand['name'] . ' ' . $series['name'] . ' ' . $model['name'];
                //所在地
                if ($val['location_area']) {
                    $location_area = $addr->get_name_by_code($val['location_area']);
                    $list[$key]['location_area'] = $location_area;
                } else {
                    $list[$key]['location_area'] = '无';
                }
            }
        }
        // dump($list);
        $result = array(
            'list' => $list,
            'total' => $total
        );
        return $result;
    }

    /**
     * 获取争议变更数据详情(详情页面)
     */
    public function dcDetail(){
        $cols = "d.*,c.brand_id,c.series_id,c.model_id,c.car_no,c.sno,ml.mid,ml.modify_no,ml.modify_reason,ml.modify_result,ml.modify_desc,ml.status as modify_status,ml.createtime as modify_createtime,ml.dealtime,ml.dealer_compensate,ml.owner_compensate,ml.dealer_deduction,ml.owner_deduction";
        $prefix = C('DB_PREFIX');
        $map = array();
        $map['d.did'] = array('eq', $this->did);
        $res = M('dispute')->alias('d')->field($cols)
            ->join($prefix . "order as o ON o.order_id = d.order_id")
            ->join($prefix . "cars as c ON c.car_id = o.car_id")
            ->join('LEFT JOIN '. $prefix . "modify_list as ml ON ml.did = d.did")
            ->where($map)->find();
        $cm = new CarModel();
        $brand = $cm->get_model_by_id($res['brand_id'], 'brand');
        $series = $cm->get_model_by_id($res['series_id'], 'series');
        $model = $cm->get_model_by_id($res['model_id']);
        $res['model'] = $brand['name'] . ' ' . $series['name'] . ' ' . $model['name'];

        $paymentIds = ChangeOrder::paymentInfoByMid($res['mid']);
        $paymentId = $paymentIds[0]['payment_id'];
        if ($paymentId) {
            $p = new Payment($paymentId);
            $pInfo = $p->getInfo();
            $res['card_no'] = $pInfo['card_no'];
            $res['bank_name'] = $pInfo['bank_name'];
            $res['account_name'] = $pInfo['account_name'];
        }
        // dump($res);
        return $res;
    }


    /**
     * 获取争议数据详情(处理页面)
     */
    public function DisputeDetail()
    {
        $cols = "d.*,c.brand_id,c.series_id,c.car_source,c.model_id,e.real_name,c.car_no,c.sno,po.purchase_order_nu,po.sid,po.amount as success_price,of.final_price,co.comefrom";
        $prefix = C('DB_PREFIX');
        $map = array();
        $map['d.did'] = array('eq', $this->did);
        $res = M('dispute')->alias('d')->field($cols)
            ->join($prefix . "order as o ON o.order_id = d.order_id")
            ->join($prefix . "cars as c ON c.car_id = o.car_id")
            ->join($prefix . "purchase_order as po ON po.id = d.po_id")
            ->join('LEFT JOIN ' . $prefix . 'car_owner as co ON c.owner_id=co.owner_id')
            ->join('LEFT JOIN ' . $prefix . "order_fee as of ON of.order_id = o.order_id")
            ->join('LEFT JOIN ' . $prefix . "recheck as rc ON rc.car_id=c.car_id")
            ->join('LEFT JOIN ' . $prefix . "employee as e ON e.emp_id=rc.condition_checker")
            ->where($map)->find();
        $cm = new CarModel();
        if ($res['od_type'] == 1) {
            $dealer = new Dealer($res['od_id']);
            $dealer_info = $dealer->detail();
            if(!empty($dealer_info)){
                $dealer_info = $dealer->get_contact_mobile_byAntNestfind($dealer_info);
            }
            $res['dealer_name'] = $dealer_info['contact_person'];
            $res['dealer_phone'] = $dealer_info['contact_mobile'];
        } else {
            $owner = new Owner($res['od_id']);
            $owner_info = $owner->detail();
            $res['owner_name'] = $owner_info['seller_name'];
            $res['owner_phone'] = $owner_info['phone'];
        }
        $brand = $cm->get_model_by_id($res['brand_id'], 'brand');
        $series = $cm->get_model_by_id($res['series_id'], 'series');
        $model = $cm->get_model_by_id($res['model_id']);
        $res['model'] = $brand['name'] . ' ' . $series['name'] . ' ' . $model['name'];
        //付款信息
        $po = new PurchaseOrder($res['po_id']);
        $payment_id = $po->getPaymentIdByPoid($res['car_source']);
        $res['real_payment'] = 0;
        if ($payment_id) {
            $p = new Payment($payment_id);
            $paymentInfo = $p ->getInfo();
            if ($paymentInfo['status'] == 1) {
                $res['real_payment'] = $paymentInfo['amount'];  //实付
            }
        }
        //收款信息
        $o = new AuOrder($res['order_id']);
        $collection_id = $o->getCollectionIdByOid();
        $res['real_collection'] = 0;
        if ($collection_id) {
            $c = new Collection($collection_id);
            $collectionInfo = $c ->getInfo();
            if ($collectionInfo['status'] == 1) {
                $res['real_collection'] = $collectionInfo['amount'] ; //实收
            }
        }
        //如果是个人车源 找到签约信息
        // if ($res['car_source'] ==2) {
        //     $sign = new Signature();
        //     $signInfo = $sign->getDetailByOrderId($res['order_id']);
        //     $res['payee_account'] = $signInfo['payee_account']; //收款人账号
        //     $res['payee_name'] = $signInfo['payee_name']; // 
        //     $res['deposit_bank'] = $signInfo['deposit_bank']; //开户行
        // }elseif ($res['car_source'] ==1) {
        //     $fours = new Fours();
        //     $fours_detail = $fours->get_fours_info(['channel_id' => $res['comefrom']]);
        //     $fours_bank_account = $fours->get_bank_account_list_by_fid($fours_detail['fid']);
        //     $fours_bank_account_total = count($fours_bank_account);
        //     $res['fours_bank_account'] = $fours_bank_account;
        //     $res['fours_bank_account_total'] = $fours_bank_account_total;
        // }
        // dump($res);
        $res['is_having_last'] = 0;
        //如果是再次争议，找到上一次变更信息
        $map = [];
        $map['did'] = $this ->did;
        $map['sid'] = $res['sid'];
        $map['is_dealer'] = $res['od_type'];
        $modifyList = self::LastDisputedetail($map); 
        if ($modifyList) {
            $res['is_having_last'] = 1;
            //该变更单产生的付款信息
            $paymentIds = ChangeOrder::paymentInfoByMid($modifyList['mid']);
            $paymentId = $paymentIds[0]['payment_id'];
            $res['last_mid'] = $modifyList['mid'];
            $res['last_modify_no'] = $modifyList['modify_no'];
            $res['last_modify_reason'] = $modifyList['modify_reason'];
            $res['last_modify_result'] = $modifyList['modify_result'];
            $res['last_modify_desc'] = $modifyList['modify_desc'];
            $res['last_status'] = $modifyList['modify_status'];
            $res['last_createtime'] = $modifyList['modify_createtime'];
            $res['last_dealer_compensate'] = $modifyList['dealer_compensate'];
            $res['last_owner_compensate'] = $modifyList['owner_compensate'];
            if ($paymentId) {
                $p = new Payment($paymentId);
                $pInfo = $p->getInfo();
                $res['last_card_no'] = $pInfo['card_no'];
                $res['last_bank_name'] = $pInfo['bank_name'];
                $res['last_account_name'] = $pInfo['account_name'];
            }
        }
        return $res;
    }

    /**关闭上一变更单以及变更生成付款信息  
    *1) 赔款->正常业务->争议
    *2) 订单关闭->变更单作废->正常业务->争议
    */
    public static function closeLastChangeInfo($mid){
        $changeInfo = ChangeOrder::getOneInfo($mid);
        $res_void_change_order = true;
        $res_void_payment = true;
        if ($changeInfo['status'] != 4) {
            //作废变更单
            $res_void_change_order = M('modify_list')->where(['mid'=>$mid])->save(['status'=>4,'is_auto_void'=>1]);
            //作废生成付款记录
            $paymentIds = ChangeOrder::paymentInfoByMid($mid);
            $paymentId = $paymentIds[0]['payment_id'];
            $res_void_payment = Payment::invalid($paymentId);
        }
        if ($res_void_change_order && $res_void_payment) {
            return true;
        }else{
            return false;
        }
    }

    /**
     * 争议审核-通过
     * 1:争议结果->通过 2:生成变更单 3:生成收款记录
     */
    public function DisputePass($data)
    {
        //事务开始
        //1:争议结果
        M()->startTrans();
        $time = date('Y-m-d H:i:s');
        $prefix = C('DB_PREFIX');
        $res_dispute = $this->detail();
        if ($res_dispute['od_type'] == self::CUSTOMER_DEALER) {
            $source = 7;
        } elseif ($res_dispute['od_type'] == self::CUSTOMER_OWNER) {
            $source = 8;
        }
        $update_dispute_data = [
            'status' => self::STATUS_ADOPT,
            'auditing_result' => 1,
            'emp_id'=>$data['emp_id'],
            'audittime' => $time
        ];
        $update_dispute = $this->update($update_dispute_data);
       
        $o = new AuOrder($res_dispute['order_id']);
        $orderInfo = $o->detail();
        $car = new Car($orderInfo['car_id']);
        $carInfo = $car->detail();
        $CarReport = new CarReportLogic($orderInfo['car_id']);
        $branch_id = $CarReport ->getBranchId();
        $p = new PurchaseOrder($res_dispute['po_id']);
        $poInfo = $p->viewById();
        //生成变更单
        $modify_no = genBillsNo('BG', '1');
        $add_modifylist_data = [
            'modify_no' => $modify_no,
            'order_id' => $res_dispute['order_id'],
            'order_no' => $res_dispute['order_no'],
            'po_id' => $res_dispute['po_id'],
            'sid' =>$poInfo['sid'],
            'po_no' => $res_dispute['po_no'],
            'car_plate_number' => $res_dispute['car_plate_number'],
            'did' => $this->did,
            'source' => $source,
            'dealer_compensate'=>$data['dealer_compensate'],
            'owner_compensate'=>$data['owner_compensate'],
            'modify_reason' => $data['modify_reason'],
            'modify_result' => $data['modify_result'],
            'modify_desc' => $data['modify_desc'],
            'status' => 1,
            'order_status' => $orderInfo['status'],
            'originator' => $data['emp_id'],
            'createtime' => $time,
            'dealtime' => $time
        ];
        $res_modifylist = M('modify_list')->add($add_modifylist_data);
        //财务记录
        /**
         * 1.车商(1赔付:au_payment生成一条争议赔付付款记录;2订单关闭：生成一条争议赔付+车款付款记录)
         * 2.车主(1赔付:au_payment生成一条争议赔付付款记录;2订单关闭：生成一条车款+争议赔付付款记录  生成一条车款-赔付收款记录)
         */
        if ($res_dispute['od_type'] == self::CUSTOMER_DEALER) {
            $dealer_payment = [
                'did' => $res_dispute['did'],
                'order_id' => $res_dispute['order_id'],
                'branch_id'=>$branch_id,
                'po_id' => $res_dispute['po_id'],
                'sid' =>$poInfo['sid'],
                'change_id' => $res_modifylist,
                'bank_account' => $data['bank_account'],
                'bank_name' => $data['bank_name'],
                'account_name' => $data['account_name'],
                'payment_amount' => $data['payment_amount'],
                'emp_id'=>$data['emp_id']
            ];
            if ($data['modify_result'] == 1) {
                $res_payment = self::dealer_owner_payment($dealer_payment, self::CUSTOMER_DEALER);
                // $res_o = $o->update(['dealer_issue_status'=>2]);
                $action = "车商争议赔付";
            } elseif ($data['modify_result'] == 2) {
                $res_payment = self::dealer_order_close($dealer_payment);
                // $res_o = $o->update(['dealer_issue_status'=>3]);
                $action = "车商争议订单关闭";
            }

        } elseif ($res_dispute['od_type'] == self::CUSTOMER_OWNER) {
            $owner_payment = [
                'did' => $res_dispute['did'],
                'order_id' => $res_dispute['order_id'],
                'po_id' => $res_dispute['po_id'],
                'sid' =>$poInfo['sid'],
                'change_id' => $res_modifylist,
                'payment_amount' => $data['payment_amount'],
                'emp_id'=>$data['emp_id']
            ];
            $payment_id =$p->getPaymentIdByPoid($carInfo['car_source']);
            if ($payment_id) {
                $payMode = new Payment($payment_id);
                $payableInfo = $payMode->getInfo();
                $owner_payment['bank_account'] = $payableInfo['card_no'];
                $owner_payment['bank_name'] = $payableInfo['bank_name'];
                $owner_payment['account_name'] = $payableInfo['account_name'];
            }else{
                $sign = new Signature();
                $sign_info = $sign ->getDetailByOrderId($poInfo['order_id']);
                $owner_payment['bank_account'] = $sign_info['payee_account'];
                $owner_payment['bank_name'] = $sign_info['deposit_bank'];
                $owner_payment['account_name'] = $sign_info['payee_name'];
            }
           
            if ($data['modify_result'] == 1) {
                $res_payment = self::dealer_owner_payment($owner_payment, self::CUSTOMER_OWNER);
                // $res_o = $o->update(['dealer_issue_status'=>2]);
                $action = "车主争议赔付";

            } elseif ($data['modify_result'] == 2) {
                $owner_payment['owner_payment_amount'] = $data['owner_payment_amount'];
                $res_payment = self::owner_order_close($owner_payment);
                // $res_o = $o->update(['dealer_issue_status'=>3]);
                $action = "车主争议订单关闭";
            }
        }
        if ($update_dispute && $res_modifylist && $res_payment) {
            //事务提交
            M()->commit();
            //记录操作日志
            $res_log = $this->record_log($res_dispute['order_id'],$orderInfo['car_id'],$data['emp_id'],$action);
            //变更表操作日志表
            $changeOrder_log = [
                'mid' => $res_modifylist,
                'emp_id' => $data['emp_id'],
                'desc' => 1,
                'createtime' => $time
            ];
            $res_changeOrder_log = M('modifylist_operation_log')->add($changeOrder_log);
            $new_changeOrder_log = [
                'mid' => $res_modifylist,
                'emp_id' => $data['emp_id'],
                'desc' => 2,
                'createtime' => $time
            ];
            $res_changeOrder_again_log = M('modifylist_operation_log')->add($new_changeOrder_log);
            return true;
        } else {
            M()->rollback();
            return false;
        }
    }

    /**
     * 争议审核-驳回
     */
    public function DisputeReject($data)
    {
        M()->startTrans();
        $time = date('Y-m-d H:i:s');
        $update_dispute_data = [
            'status' => self::STATUS_REJECT,
            'auditing_result' => 2,
            'reject_result' => $data['reject_result'],
            'audittime' => $time
        ];
        $update_dispute = M('dispute')->where(['did' => $this->did])->save($update_dispute_data);
        $disputeInfo = $this->detail();
        $o = new AuOrder($disputeInfo['order_id']);
        $orderInfo = $o ->detail();
        $map = [];
        $map['order_id'] = $disputeInfo['order_id'];
        $map['po_id'] = $disputeInfo['po_id'];
        //拍单争议状态
        $res_o = $o->update(['dealer_issue_status'=>0,'is_dealer_issue'=>0]);
        //解锁
        $res_unLockAll = self::unLockAll($map);
        if ($update_dispute && $res_unLockAll && $res_o) {
            //事务提交
            M()->commit();
            //记录操作日志
            $res_log = $this->record_log($disputeInfo['order_id'],$orderInfo['car_id'],$data['emp_id'],'争议驳回');
            return true;
        } else {
            M()->rollback();
            return false;
        }
    }

    /**
     * 争议审核-违约
     * 1:争议结果->违约 2:生成变更单 3:生成收款记录
     */
    public function DisputeViolate($data)
    {
        //事务开始
        //1:争议结果
        M()->startTrans();
        $time = date('Y-m-d H:i:s');
        $res_dispute = $this->detail();
        if ($res_dispute['od_type'] == self::CUSTOMER_DEALER)
            $source = 7;
        elseif ($res_dispute['od_type'] == self::CUSTOMER_OWNER)
            $source = 8;
        $update_dispute_data = [
            'status' => self::STATUS_REJECT,
            'emp_id' =>$data['emp_id'],
            'auditing_result' => 3,
            'reject_result' =>'已跟商户沟通，争议驳回且判为违约',
            'audittime' => $time
        ];
        $update_dispute = M('dispute')->where(['did' => $this->did])->save($update_dispute_data);
        
        $o = new AuOrder($res_dispute['order_id']);
        $orderInfo = $o ->detail();
        $CarReport = new CarReportLogic($orderInfo['car_id']);
        $branch_id = $CarReport ->getBranchId();
        $p = new PurchaseOrder($res_dispute['po_id']);
        $poInfo = $p ->viewById();
        $modify_no = genBillsNo('BG', '1');
        $add_modifylist_data = [
            'modify_no' => $modify_no,
            'order_id' => $res_dispute['order_id'],
            'order_no' => $res_dispute['order_no'],
            'po_id' => $res_dispute['po_id'],
            'po_no' => $res_dispute['po_no'],
            'sid' =>$poInfo['sid'],
            'car_plate_number' => $res_dispute['car_plate_number'],
            'did' => $this->did,
            'source' => $source,
            'dealer_compensate'=>$data['dealer_compensate'],
            'dealer_deduction'=>$data['dealer_deduction'],
            'owner_deduction'=>$data['owner_deduction'],
            'modify_reason' => $data['modify_reason'],
            'modify_result'=>2,
            'modify_desc' => $data['modify_desc'],
            'status' => 1,
            'order_status' => $orderInfo['status'],
            'originator' => $data['emp_id'],
            'createtime' => $time,
            'dealtime' => $time
        ];
        $res_modifylist = M('modify_list')->add($add_modifylist_data);
        //财务
        $dealer_payment = [
            'did' => $res_dispute['did'],
            'order_id' => $res_dispute['order_id'],
            'po_id' => $res_dispute['po_id'],
            'sid' =>$poInfo['sid'],
            'branch_id'=>$branch_id,
            'change_id' => $res_modifylist,
            'payment_amount' => $data['payment_amount'],
            'owner_payment_amount'=>$data['owner_payment_amount'],
            'bank_account' => $data['bank_account'],
            'bank_name' => $data['bank_name'],
            'account_name' => $data['account_name'],
            'emp_id'=>$data['emp_id']
        ];
        if ($data['modify_reason'] == 3) {
            //买方违约 即车商违约 车辆流入违约车辆列表中 
            $res_violate = self::dealer_violate($dealer_payment);
            $action = "争议处理,买方违约";

        } elseif ($data['modify_reason'] == 4) {
            //卖方违约 即车主违约 订单关闭
            $res_violate = self::owner_violate($dealer_payment);
            $action = "争议处理,卖方违约";
        }
        if ($update_dispute && $res_modifylist && $res_violate) {
            //事务提交
            M()->commit();
            //记录操作日志
            $res_log = $this->record_log($res_dispute['order_id'],$orderInfo['car_id'],$data['emp_id'],$action);
            //变更表操作日志表
            $changeOrder_log = [
                'mid' => $res_modifylist,
                'emp_id' => $data['emp_id'],
                'desc' => 1,
                'createtime' => $time
            ];
            $res_changeOrder_log = M('modifylist_operation_log')->add($changeOrder_log);
            $new_changeOrder_log = [
                'mid' => $res_modifylist,
                'emp_id' => $data['emp_id'],
                'desc' => 2,
                'createtime' => $time
            ];
            $res_changeOrder_again_log = M('modifylist_operation_log')->add($new_changeOrder_log);
            return true;
        } else {
            M()->rollback();
            return false;
        }
    }

    // /**付款类型**/
    // 'PAYMENT_TYPE' => [
        // 1 => '采购应付',
        // 2 => '采购应付（首）',
        // 3 => '采购应付（尾）',
        // 4 => '应退车商',
        // 5 => '车商赔付',
        // 6 => '车主赔付',
        // 7 => '贷款首付款退还',
    // ],
    // /**收款类型**/
    // 'COLLECTION_TYPE' => [
        // 1 => '车款应收',
        // 2 => '金融贷款（全款）',
        // 3 => '金融贷款（首款）',
        // 4 => '金融贷款（尾款）',
        // 5 => '保证金充值',
        // 6 => '保证金违约扣除',
        // 7 => '车主应收',
        // 8 => '车主违约金扣除',
        // 9 => '查询结算',
        // 10 =>'车商违约金扣除'
    // ]

    //车商车主赔付
    public static function dealer_owner_payment($data, $is_dealer_owner)
    {
        $o = new AuOrder($data['order_id']);
        $res_payment = true;
        $res_paymentrelevant = true;
        $time = date('Y-m-d H:i:s');
        if ($data['payment_amount'] > 0) {
            $payment_data = [
                'pay_way' => 1, //1转账
                'create_time' => $time,
                'branch_id' =>$data['branch_id'],
                'status' => -1,
                'card_no' => $data['bank_account'],
                'bank_name' => $data['bank_name'],
                'account_name' => $data['account_name']
            ];
            if ($is_dealer_owner == self::CUSTOMER_DEALER) {
                $payment_data['pay_type'] = 5;
            } else {
                $payment_data['pay_type'] = 6;
            }
            $payment_data['amount'] = $data['payment_amount'];
            $res_payment = Payment::add($payment_data);
            $prData = [
                'change_id' => $data['change_id'],
                'payment_id' => $res_payment,
                'pay_type' => $payment_data['pay_type']
            ];
            //变更单生成付款信息中间表
            $res_paymentrelevant = ChangeOrder::addPaymentRelevant($prData);
        }else{
            $res_co_succ = ChangeOrder::changeOrderSucc($data['change_id']);
        }
        
        //找到上一变更单赔款，作废上一变更单以及付款
        $res_void_last_change = true;
        $lastData = [];
        $lastData['sid'] = $data['sid'];
        $lastData['mid'] = $data['change_id'];
        $lastData['is_dealer'] = $is_dealer_owner;//车主
        $last_change_info = ChangeOrder::getLastChangeOrder($lastData);
        if ($last_change_info) {
            $res_void_last_change = ChangeOrder::voidLastChange($last_change_info['mid']);
        }
        //修改拍单争议状态
        $res_dis_status = $o ->update(['dealer_issue_status'=>2,'is_dealer_issue'=>0]);
        //解锁
        $res_unLockAll = self::unLockAll($data);
        if ($res_payment && $res_paymentrelevant && $res_unLockAll && $res_dis_status && $res_void_last_change) {
            return true;
        } else {
            return false;
        }
    }
    //车主争议->订单关闭
    /**
     * @param $data
     * @return bool
     */
    public static function owner_order_close($data)
    {
        $o = new AuOrder($data['order_id']);
        $time = date('Y-m-d H:i:s');
        $payment_data = [
            'pay_way' => 1, //1转账
            'create_time' => $time,
            'status' => 0,
            'branch_id' =>$data['branch_id'],
            'card_no' => $data['bank_account'],
            'bank_name' => $data['bank_name'],
            'account_name' => $data['account_name']
        ];
       
        //车商赔偿
        $res_payment = true;
        $res_paymentrelevant = true;
        $o = new AuOrder($data['order_id']);
        $orderInfo = $o->detail();
        $collection_id = $o->getCollectionIdByOid();
        if (!$collection_id) {
            $payment_data['pay_type'] = 5;
            $payment_data['amount'] = $data['payment_amount'];
        }else{
            $c = new Collection($collection_id);
            $collection_info = $c ->getInfo();
            if ($collection_info['status'] == 2) {
                $payment_data['pay_type'] = 5;
                $payment_data['amount'] = $data['payment_amount'];
            } elseif ($collection_info['status'] == 1) {
                $payment_data['pay_type'] = 4;
                $payment_data['amount'] = $data['payment_amount'] + $collection_info['amount'];
            }
        }
        if ($payment_data['amount'] > 0) {
            $res_payment = Payment::add($payment_data);
            $prData = [
                'change_id' => $data['change_id'],
                'payment_id' => $res_payment,
                'pay_type' => $payment_data['pay_type']
            ];
            //变更单生成付款信息中间表
            $res_paymentrelevant = ChangeOrder::addPaymentRelevant($prData);
        }

        //车主赔偿
        $res_owner_payment = true;
        $res_owner_paymentrelevant = true;
        $payment_data_owner = [
            'pay_way' => 1, //1转账
            'create_time' => $time,
            'status' => 0,
            'branch_id' =>$data['branch_id'],
            'card_no' => $data['bank_account'],
            'bank_name' => $data['bank_name'],
            'account_name' => $data['account_name']
        ];
        $po = new PurchaseOrder($data['po_id']);
        $Car = new Car($orderInfo['car_id']);
        $carInfo = $Car ->detail();
        $payment_id = $po->getPaymentIdByPoid($carInfo['car_source']);
        if (!$payment_id) {
            $payment_data_owner['pay_type'] = 6;
            $payment_data_owner['amount'] = $data['owner_payment_amount'];
            if ($payment_data_owner['amount'] > 0) {
                $res_owner_payment = Payment::add($payment_data_owner);
                $prData = [
                    'change_id' => $data['change_id'],
                    'payment_id' => $res_owner_payment,
                    'pay_type' => $payment_data_owner['pay_type']
                ];
                //变更单生成付款信息中间表
                $res_owner_paymentrelevant = ChangeOrder::addPaymentRelevant($prData);
            }
        }else{
            $payment = new Payment($payment_id);
            $payment_info = $payment->getInfo();
            if ($payment_info['status'] == 2) {
                $payment_data_owner['pay_type'] = 6;
                $payment_data_owner['amount'] = $data['owner_payment_amount'];
                if ($payment_data_owner['amount'] > 0) {
                    $res_owner_payment = Payment::add($payment_data_owner);
                    $prData = [
                        'change_id' => $data['change_id'],
                        'payment_id' => $res_owner_payment,
                        'pay_type' => $payment_data_owner['pay_type']
                    ];
                    //变更单生成付款信息中间表
                    $res_owner_paymentrelevant = ChangeOrder::addPaymentRelevant($prData);
                }
            } elseif ($payment_info['status'] == 1) {
                //已付车主
                if ($data['owner_payment_amount'] > $payment_info['amount']) {
                    $payment_data_owner['pay_type'] = 6;
                    $payment_data_owner['amount'] = $data['owner_payment_amount'] - $payment_info['amount'];
                    if ($payment_data_owner['amount'] > 0) {
                        $res_owner_payment = Payment::add($payment_data_owner);
                        $prData = [
                            'change_id' => $data['change_id'],
                            'payment_id' => $res_owner_payment,
                            'pay_type' => $payment_data_owner['pay_type']
                        ];
                        //变更单生成付款信息中间表
                        $res_owner_paymentrelevant = ChangeOrder::addPaymentRelevant($prData);
                    }
                } elseif ($data['owner_payment_amount'] < $payment_info['amount']) {
                    $payment_data_owner = [];
                    $payment_data_owner = [
                        'payment_method' => 1, //1转账
                        'create_time' => $time,
                        'status' => 0,
                        'branch_id' =>$data['branch_id'],
                        'payment_type'=>7
                    ];
                    $payment_data_owner['amount'] = $payment_info['amount'] - $data['owner_payment_amount'];
                    if ($payment_data_owner['amount'] > 0) {
                        $res_owner_payment = Collection::add($payment_data_owner);
                        $ccData = [
                            'change_id' => $data['change_id'],
                            'collection_id' => $res_owner_payment,
                            'payment_type' => $payment_data_owner['payment_type']
                        ];
                        //变更单生成付款信息中间表
                        $res_owner_paymentrelevant = ChangeOrder::addCollectionRelevant($ccData);
                    }
                }elseif ($data['owner_payment_amount'] == $payment_info['amount']) {
                    $res_co_succ = ChangeOrder::changeOrderSucc($data['change_id']);
                }
            }
        }
        if ($payment_data['amount'] == 0 && $payment_data_owner['amount'] == 0) {
            $res_co_succ = ChangeOrder::changeOrderSucc($data['change_id']);
        }
        
        //解冻保证金
        $res_bail = AssetCenter::unfreeze($orderInfo['success_dealer_id'],$data['order_id']);

        //修改拍单争议状态
        $res_dis_status = $o ->update(['dealer_issue_status'=>4]);

        //如果是过户产生的违约，需要将其放到过户失败里面
        if (in_array($orderInfo['status'],[9,10])) {
            $trans = new Transfer($data['order_id']);
            $transData = [];
            $transData['result'] = 3;
            $transData['last_update'] = $time;
            $transfer = $trans ->update($transData);
        }

        //订单关闭
        $res_order = $o->unLockFailByOrderId();
        ///采购单关闭
        $po = new PurchaseOrder($data['po_id']);
        $res_purchase_order = $po->closeById();
        //付款单作废(采购单)
        $res_payment_status = true;
        if ($payment_id && $payment_info['status'] == 2) {
            $res_payment_status = Payment::invalid($payment_id);
        }
        
        //收款单作废(拍单)
        $res_collection = true;
        if ($collection_id && $collection_info['status'] == 2) {
            $res_collection = Collection::invalid($collection_id);
        }

        //找到上一变更单赔款，作废上一变更单以及付款
        $res_void_last_change = true;
        $lastData = [];
        $lastData['sid'] = $data['sid'];
        $lastData['mid'] = $data['change_id'];
        // $lastData['is_dealer'] = 3;//车商车主
        $last_change_info = ChangeOrder::getOwnerVoidChangeOrder($lastData);
        if ($last_change_info) {
            foreach ($last_change_info as $key => $value) {
                $res_void_last_change = ChangeOrder::voidLastChange($value['mid']);
            }
        }
        //更改cars状态
        $res_cars = $Car->update(['car_status' => 8]);
        // dump($res_void_last_change);
        // dump($res_payment);
        // dump($res_paymentrelevant);
        // dump($res_owner_payment);
        // dump($res_owner_paymentrelevant);
        // dump($res_order);
        // dump($res_purchase_order);
        // dump($res_payment_status);
        // dump($res_collection);
        // dump($res_dis_status);
        // die();
        if ($res_void_last_change && $res_payment && $res_paymentrelevant && $res_owner_payment && $res_owner_paymentrelevant && $res_order && $res_purchase_order && $res_payment_status && $res_collection && $res_dis_status) {
            return true;
        } else {
            return false;
        }
    }

    //车商争议->订单关闭  车辆流入违约车辆列表中 
    public static function dealer_order_close($data)
    {   
        $o = new AuOrder($data['order_id']);
        $res_payment = true;
        $res_paymentrelevant = true;
        $time = date('Y-m-d H:i:s');
        $payment_data = [
            'pay_way' => 1, //1转账
            'create_time' => $time,
            'status' => 0,
            'branch_id' =>$data['branch_id'],
            'card_no' => $data['bank_account'],
            'bank_name' => $data['bank_name'],
            'account_name' => $data['account_name']
        ];
        $orderInfo = $o->detail();
        $collection_id = $o->getCollectionIdByOid();
        if (!$collection_id) {
            $payment_data['pay_type'] = 5;
            $payment_data['amount'] = $data['payment_amount'];
        }else{
            $c = new Collection($collection_id);
            $collection_info = $c ->getInfo();
            if ($collection_info['status'] == 2) {
                $payment_data['pay_type'] = 5;
                $payment_data['amount'] = $data['payment_amount'];
            } elseif ($collection_info['status'] == 1) {
                $payment_data['pay_type'] = 4;
                $payment_data['amount'] = $data['payment_amount'] + $collection_info['amount'];
            }
        }
        if ($payment_data['amount'] > 0) {
            $res_payment = Payment::add($payment_data);
            $prData = [
                'change_id' => $data['change_id'],
                'payment_id' => $res_payment,
                'pay_type' => $payment_data['pay_type']
            ];
            //变更单生成付款信息中间表
            $res_paymentrelevant = ChangeOrder::addPaymentRelevant($prData);
        }else{
            $res_co_succ = ChangeOrder::changeOrderSucc($data['change_id']);
        }
        

        //解冻保证金
        $res_bail = AssetCenter::unfreeze($orderInfo['success_dealer_id'],$data['order_id']);

        //如果是过户产生的违约，需要将其放到过户失败里面
        if (in_array($orderInfo['status'],[9,10])) {
            $trans = new Transfer($data['order_id']);
            $transData = [];
            $transData['result'] = 3;
            $transData['last_update'] = $time;
            $transfer = $trans ->update($transData);
        }

        //拍单解锁失败
        $res_order = $o->unLockFailByOrderId();

        //是否是自收车辆 是自收流到自收车辆 否流入违约车辆

        $car = new Car($orderInfo['car_id']);
        $carInfo = $car ->detail();
        $breach_car_info = array(
            'sid' => $carInfo['sid'],
            'car_id' => $orderInfo['car_id'],
            'did' => $data['did'],
            'mid' => $data['change_id'],
            'order_id'=>$data['order_id'],
        );
        if ($carInfo['is_self_receive'] == 1) {
            $breach_car_info['createtime'] = $time;
            $resCar = SelfReceiveCar::create($breach_car_info);
        }else{
            $breach_car_info['create_time'] = $time;
            $resCar = BreachCar::create($breach_car_info);
        }

        //收款单作废(拍单)
        $res_collection = true;
        if ($collection_id && $collection_info['status'] == 2) {
            $res_collection = Collection::invalid($collection_id);
        }
        //修改拍单争议状态
        $res_dis_status = $o ->update(['dealer_issue_status'=>4]);
        //找到上一变更单赔款，作废上一变更单以及付款
        $res_void_last_change = true;
        $lastData = [];
        $lastData['sid'] = $data['sid'];
        $lastData['mid'] = $data['change_id'];
        $lastData['is_dealer'] = 1;//车商
        $last_change_info = ChangeOrder::getLastChangeOrder($lastData);
        if ($last_change_info) {
            $res_void_last_change = ChangeOrder::voidLastChange($last_change_info['mid']);
        }
        if ($res_void_last_change && $res_payment && $res_paymentrelevant && $res_order && $resCar && $res_collection && $res_dis_status !== false) {
            return true;
        } else {
            return false;
        }
    }


    //违约->车商违约   车辆流入违约车辆列表中 
    public static function dealer_violate($data)
    {   
        $o = new AuOrder($data['order_id']);
        $orderInfo = $o->detail();
        $dispute_info = self::getOneInfo($data['did']);
        $time = date('Y-m-d H:i:s');
        $payment_data = [
            'pay_way' => 1, //1转账
            'create_time' => $time,
            'status' => 0,
            'branch_id' =>$data['branch_id'],
            'card_no' => $data['bank_account'],
            'bank_name' => $data['bank_name'],
            'account_name' => $data['account_name']
        ];
        $collection_data = [
            'payment_method' => 1, //1转账
            'branch_id' =>$data['branch_id'],
            'create_time' => $time,
            'status' => 0
        ];
        //找到上一变更单赔款，作废上一变更单以及付款
        $res_void_last_change = true;
        $lastData = [];
        $lastData['sid'] = $data['sid'];
        $lastData['mid'] = $data['change_id'];
        $lastData['is_dealer'] = 1;//车商
        $last_change_info = ChangeOrder::getLastChangeOrder($lastData);
        if ($last_change_info) {
            $res_void_last_change = ChangeOrder::voidLastChange($last_change_info['mid']);
        }

        //是否收过车商款 是:生成退款记录（违约金）   否：扣除保证金 生成
        $res_pc = true;
        $res_paymentrelevant = true;
        $collection_id = $o->getCollectionIdByOid();
        if (!$collection_id) {
            $assertCenter = new AssetCenter($dispute_info['od_id']);
            $assertParams = array(
                'order_id' => $data['order_id'],
                'dealer_id' => $dispute_info['od_id'],
                'order_no' => $orderInfo['order_no'],
                'occur_money' => $data['payment_amount']// 发生金额
            );
            $resViolateBail = $assertCenter->occurViolate($assertParams);
            if ($resViolateBail) {
                //生成一条收款记录（已收）
                if ($data['payment_amount'] > 0) {
                    $collection_data['payment_type'] = 6;//保证金违约扣除
                    $collection_data['amount'] = $data['payment_amount'];
                    $collection_data['status'] = 1;
                    $collection_data['emp_name'] = '系统';
                    $collection_data['emp_id'] = C('SYSTEM_EMP_ID.0');
                    $collection_data['update_time'] = $time;
                    $res_pc = Collection::add($collection_data);
                    $ccData = [
                        'change_id' => $data['change_id'],
                        'collection_id' => $res_pc,
                        'payment_type' => $collection_data['payment_type']
                    ];
                    //变更单生成付款信息中间表
                    $res_paymentrelevant = ChangeOrder::addCollectionRelevant($ccData);
                };
                //扣保证金 变更单已完成
                $res_co_succ = ChangeOrder::changeOrderSucc($data['change_id']);
                
            } else {
                return false;
            }
        }else{
            $c = new Collection($collection_id);
            $collection_info = $c ->getInfo();
            // $collection_info = Collection::getCollectionByIds($collection_id);
            if ($collection_info['status'] == 1) {
                if ($data['payment_amount'] > $collection_info['amount']) {
                    $collection_data['amount'] = $data['payment_amount'] - $collection_info['amount'];
                    $collection_data['payment_type'] = 6;
                    $collection_data['status'] = 1;
                    $collection_data['emp_name'] = '系统';
                    $collection_data['emp_id'] = C('SYSTEM_EMP_ID.0');
                    $collection_data['update_time'] = $time;
                    $assertCenter = new AssetCenter($dispute_info['od_id']);
                    $assertParams = array(
                        'order_id' => $data['order_id'],
                        'dealer_id' => $dispute_info['od_id'],
                        'order_no' => $orderInfo['order_no'],
                        'occur_money' =>$collection_data['amount']// 发生金额
                    );
                    $resViolateBail = $assertCenter->occurViolate($assertParams);
                    if ($resViolateBail) {
                        if ($collection_data['amount'] > 0) {
                            //生成一条收款记录（已收）
                            $res_pc = Collection::add($collection_data);
                            $ccData = [
                                'change_id' => $data['change_id'],
                                'collection_id' => $res_pc,
                                'payment_type' => $collection_data['payment_type']
                            ];
                            //变更单生成付款信息中间表
                            $res_paymentrelevant = ChangeOrder::addCollectionRelevant($ccData);
                        }
                        //扣保证金 变更单已完成
                        $res_co_succ = ChangeOrder::changeOrderSucc($data['change_id']);
                    } else {
                        return false;
                    }
                } elseif ($data['payment_amount'] < $collection_info['amount']) {
                    $payment_data['pay_type'] = 4;
                    $payment_data['amount'] = $collection_info['amount'] - $data['payment_amount'];
                    if ($payment_data['amount'] > 0) {
                        $res_pc = Payment::add($payment_data);
                        $prData = [
                            'change_id' => $data['change_id'],
                            'payment_id' => $res_pc,
                            'pay_type' => $payment_data['pay_type']
                        ];
                        //变更单生成付款信息中间表
                        $res_paymentrelevant = ChangeOrder::addPaymentRelevant($prData);
                    }else{
                        $res_co_succ = ChangeOrder::changeOrderSucc($data['change_id']);
                    }
                    //解冻保证金
                    $res_bail = AssetCenter::unfreeze($orderInfo['success_dealer_id'],$data['order_id']);
                }elseif ($data['payment_amount'] == $collection_info['amount']) {
                    $res_co_succ = ChangeOrder::changeOrderSucc($data['change_id']);
                }
            } elseif ($collection_info['status'] == 2) {
                $assertCenter = new AssetCenter($dispute_info['od_id']);
                $assertParams = array(
                    'order_id' => $data['order_id'],
                    'dealer_id' => $dispute_info['od_id'],
                    'order_no' => $orderInfo['order_no'],
                    'occur_money' => $data['payment_amount']// 发生金额
                );
                $resViolateBail = $assertCenter->occurViolate($assertParams);
                if ($resViolateBail) {
                    //生成一条收款记录（已收）
                    if ($data['payment_amount'] > 0) {
                        $collection_data['payment_type'] = 6;//保证金违约扣除
                        $collection_data['amount'] = $data['payment_amount'];
                        $collection_data['status'] = 1;
                        $collection_data['emp_name'] = '系统';
                        $collection_data['emp_id'] = C('SYSTEM_EMP_ID.0');
                        $collection_data['update_time'] = $time;
                        $res_pc = Collection::add($collection_data);
                        $ccData = [
                            'change_id' => $data['change_id'],
                            'collection_id' => $res_pc,
                            'payment_type' => $collection_data['payment_type']
                        ];
                        //变更单生成付款信息中间表
                        $res_paymentrelevant = ChangeOrder::addCollectionRelevant($ccData);
                    }
                    $res_co_succ = ChangeOrder::changeOrderSucc($data['change_id']);
                } else {
                    return false;
                }
            }
        }
    
        //是否是自收车辆 是自收流到自收车辆 否流入违约车辆

        $car = new Car($orderInfo['car_id']);
        $carInfo = $car ->detail();
        $breach_car_info = array(
            'sid' => $carInfo['sid'],
            'car_id' => $orderInfo['car_id'],
            'did' => $data['did'],
            'mid' => $data['change_id'],
            'order_id'=>$data['order_id']
        );
        if ($carInfo['is_self_receive'] == 1) {
            $breach_car_info['createtime'] = $time;
            $resCar = SelfReceiveCar::create($breach_car_info);
        }else{
            $breach_car_info['create_time'] = $time;
            $resCar = BreachCar::create($breach_car_info);
        }

        //如果是过户产生的违约，需要将其放到过户失败里面
        if (in_array($orderInfo['status'],[9,10])) {
            $trans = new Transfer($data['order_id']);
            $transData = [];
            $transData['result'] = 3;
            $transData['last_update'] = $time;
            $transfer = $trans ->update($transData);
        }

        //拍单解锁关闭
        $res_order = $o->unLockFailByOrderId();

        //收款单作废(拍单)
        $res_collection = true;
        if ($collection_id && $collection_info['status'] == 2) {
            $res_collection = Collection::invalid($collection_id);
        }
        
        //修改拍单争议状态
        $res_dis_status = $o ->update(['dealer_issue_status'=>3]);

        if ($res_void_last_change && $res_pc && $res_paymentrelevant && $resCar && $res_order && $res_collection && $res_dis_status) {
            return true;
        } else {
            return false;
        }
    }

    //违约->车主违约  订单关闭
    public static function owner_violate($data)
    {   
        $o = new AuOrder($data['order_id']);
        $dispute_info = self::getOneInfo($data['did']);
        $time = date('Y-m-d H:i:s');
        //找到上一变更单赔款，作废上一变更单以及付款
        $res_void_last_change = true;
        $lastData = [];
        $lastData['sid'] = $data['sid'];
        $lastData['mid'] = $data['change_id'];
        // $lastData['is_dealer'] = 3;//车商车主
        $last_change_info = ChangeOrder::getOwnerVoidChangeOrder($lastData);
        if ($last_change_info) {
            foreach ($last_change_info as $key => $value) {
                $res_void_last_change = ChangeOrder::voidLastChange($value['mid']);
            }
        }
        $res_payment = true; 
        $res_paymentrelevant = true;
        //是否收过车商款
        $payment_data = [
            'pay_way' => 1, //1转账
            'create_time' => $time,
            'status' => 0,
            'branch_id' =>$data['branch_id'],
            'card_no' => $data['bank_account'],
            'bank_name' => $data['bank_name'],
            'account_name' => $data['account_name']
        ];
        $orderInfo = $o->detail();
        $collection_id = $o->getCollectionIdByOid();
        if (!$collection_id) {
            $payment_data['pay_type'] = 5;
            $payment_data['amount'] = $data['payment_amount'];
        }else{
            $c = new Collection($collection_id);
            $collection_info = $c ->getInfo();
            if ($collection_info['status'] == 2) {
                $payment_data['pay_type'] = 5;
                $payment_data['amount'] = $data['payment_amount'];
            } elseif ($collection_info['status'] == 1) {
                $payment_data['pay_type'] = 4;
                $payment_data['amount'] = $data['payment_amount'] + $collection_info['amount'];
            }
        }
        if ($payment_data['amount'] > 0) {
            $res_payment = Payment::add($payment_data);
            $prData = [
                'change_id' => $data['change_id'],
                'payment_id' => $res_payment,
                'pay_type' => $payment_data['pay_type']
            ];
            //变更单生成付款信息中间表
            $res_paymentrelevant = ChangeOrder::addPaymentRelevant($prData);
        }
        
        
        //车主 是否付款 是：生成收款记录（违约金+付款）   否：生成收款记录（违约金）
        $collection_data = [
            'payment_method' => 1, //1转账
            'branch_id' =>$data['branch_id'],
            'create_time' => $time,
            'status' => 0
        ];
        $res_owner_payment = true;
        $res_owner_paymentrelevant = true;
        $po = new PurchaseOrder($data['po_id']);
        $Car = new Car($orderInfo['car_id']);
        $carInfo = $Car ->detail();
        $payment_id = $po->getPaymentIdByPoid($carInfo['car_source']);
        if (!$payment_id) {
            $collection_data['payment_type'] = 8;
            $collection_data['amount'] = $data['owner_payment_amount'];
            if ($collection_data['amount'] > 0) {
                $res_owner_payment = Collection::add($collection_data);
                $ccData = [
                    'change_id' => $data['change_id'],
                    'collection_id' => $res_owner_payment,
                    'payment_type' => $collection_data['payment_type']
                ];
                //变更单生成付款信息中间表
                $res_owner_paymentrelevant = ChangeOrder::addCollectionRelevant($ccData);
            }
        }else{
            $payment = new Payment($payment_id);
            $payment_info = $payment->getInfo();
            if ($payment_info['status'] == 2) {
                $collection_data['payment_type'] = 8;
                $collection_data['amount'] = $data['owner_payment_amount'];
                if ($collection_data['amount'] > 0) {
                    $res_owner_payment = Collection::add($collection_data);
                    $ccData = [
                        'change_id' => $data['change_id'],
                        'collection_id' => $res_owner_payment,
                        'payment_type' => $collection_data['payment_type']
                    ];
                    //变更单生成付款信息中间表
                    $res_owner_paymentrelevant = ChangeOrder::addCollectionRelevant($ccData);
                }
            } elseif ($payment_info['status'] == 1) {
                //车主应收
                $collection_data['payment_type'] = 7;
                $collection_data['amount'] = $payment_info['amount'];
                $res_owner_payment = Collection::add($collection_data);
                $ccData = [
                    'change_id' => $data['change_id'],
                    'collection_id' => $res_owner_payment,
                    'payment_type' => $collection_data['payment_type']
                ];
                //变更单生成付款信息中间表
                $res_owner_paymentrelevant = ChangeOrder::addCollectionRelevant($ccData);
                if ($res_owner_payment && $res_owner_paymentrelevant) {
                    //车主违约金扣除
                    $collection_data['payment_type'] = 8;
                    $collection_data['amount'] = $data['owner_payment_amount'];
                    if ($collection_data['amount'] > 0) {
                        $res_owner_payment = Collection::add($collection_data);
                        $ccData = [
                            'change_id' => $data['change_id'],
                            'collection_id' => $res_owner_payment,
                            'payment_type' => $collection_data['payment_type']
                        ];
                        //变更单生成付款信息中间表
                        $res_owner_paymentrelevant = ChangeOrder::addCollectionRelevant($ccData);
                    }
                }else{
                    return false;
                }
            }
        }

        if ($payment_data['amount'] == 0 && $collection_data['amount'] == 0) {
            $res_co_succ = ChangeOrder::changeOrderSucc($data['change_id']);
        }
        //解冻保证金
        $res_bail = AssetCenter::unfreeze($orderInfo['success_dealer_id'],$data['order_id']);

        //如果是过户产生的违约，需要将其放到过户失败里面
        if (in_array($orderInfo['status'],[9,10])) {
            $trans = new Transfer($data['order_id']);
            $transData = [];
            $transData['result'] = 3;
            $transData['last_update'] = $time;
            $transfer = $trans ->update($transData);
        }

        $res_order = $o->unLockFailByOrderId();

        ///采购单关闭
        $po = new PurchaseOrder($data['po_id']);
        $res_purchase_order = $po->closeById();

        //付款单作废(采购单)
        $res_payment_status = true; 
        if ($payment_id && $payment_info['status'] == 2) {
            $res_payment_status = Payment::invalid($payment_id);
        }
        
        //收款单作废(拍单)
        $res_collection = true;
        if ($collection_id && $collection_info['status'] == 2) {
            $res_collection = Collection::invalid($collection_id);
        }
        
        //修改拍单争议状态
        $res_dis_status = $o ->update(['dealer_issue_status'=>5]);

        //更改车源状态
        $CarSource = new CarSource($carInfo['sid']);
        $csData = [];
        $csData['status'] = 600;
        $res_cs = $CarSource->update($csData);
        //更改cars状态
        $res_cars = $Car->update(['car_status' => 8]);
        // dump($res_void_last_change);
        // dump($res_payment);
        // dump($res_paymentrelevant);
        // dump($res_owner_payment);
        // dump($res_owner_paymentrelevant);
        // dump($res_order);
        // dump($res_purchase_order);
        // dump($res_payment_status);
        // dump($res_collection);
        // dump($res_dis_status);
        // die();
        if ($res_void_last_change && $res_payment && $res_paymentrelevant && $res_owner_payment && $res_owner_paymentrelevant && $res_order && $res_purchase_order && $res_payment_status && $res_collection && $res_dis_status) {
            return true;
        } else {
            return false;
        }
    }

    private static function lockAll($data){
        //拍单锁定
        $o = new AuOrder($data['order_id']);
        $orderInfo = $o->detail();
        $res_order = $o->lockByOrderId();
        ///采购单锁定
        $po = new PurchaseOrder($data['po_id']);
        $po_info = $po ->viewById();
        $res_purchase_order = $po->lockById();

        //付款单锁定(采购单)
        $Car = new Car($orderInfo['car_id']);
        $carInfo = $Car ->detail();
        $payment_id = $po->getPaymentIdByPoid($carInfo['car_source']);
        $res_payment = true;
        if ($payment_id) {
            $payment = new Payment($payment_id);
            $payment_info = $payment->getInfo();
            if ($payment_info['status'] == 0) {
                $res_payment = Payment::lock($payment_id);
            }
        }
        //收款锁定(拍单)
        $collection_id = $o->getCollectionIdByOid();
        $res_collection = true;
        if ($collection_id) {
            $c = new Collection($collection_id);
            $collection_info = $c ->getInfo();
            if ($collection_info['status'] == 0) {
                $res_collection = Collection::lock($collection_id);
            }
        }
        if ($res_order && $res_purchase_order && $res_payment && $res_collection ) {

            return true;
        }else{
            return false;
        }
    }
    private static function unLockAll($data){
        //拍单解锁
        $o = new AuOrder($data['order_id']);
        $orderInfo = $o->detail();
        $res_order = $o->unLockByOrderId();

        ///采购单解锁
        $po = new PurchaseOrder($data['po_id']);
        $po_info = $po ->viewById();
        $res_purchase_order = $po->unLockById();
        // echo M()->_sql();

        //付款单解锁(采购单)
        $Car = new Car($orderInfo['car_id']);
        $carInfo = $Car ->detail();
        $payment_id = $po->getPaymentIdByPoid($carInfo['car_source']);
        $res_payment = true;
        if ($payment_id) {
            $payment = new Payment($payment_id);
            $payment_info = $payment->getInfo();
            if ($payment_info['status'] == 2) {
                $res_payment = Payment::unLock($payment_id);
            }
        }
        //收款解锁(拍单)
        $collection_id = $o->getCollectionIdByOid();
        $res_collection = true;
        if ($collection_id) {
            $c = new Collection($collection_id);
            $collection_info = $c ->getInfo();
            if ($collection_info['status'] == 2) {
                $res_collection = Collection::unLock($collection_id);
            }
        }
        if ($res_order && $res_purchase_order && $res_payment && $res_collection ) {
            return true;
        }else{
            return false;
        }
    }

   private function record_log($order_id, $car_id,$emp_id,$action)
    {
        //记录员工操作日志
        $log = [
            'emp_id' => $emp_id,
            'order_id' => $order_id,
            'car_id' => $car_id,
            'owner_id' => 0,
            'action' => $action
        ];
        \AuctionCore\System\SystemLog::add($log);

        /**
         * 记录车辆跟踪日志
         */
        $car_action_data = array(
            'action_name' => $action,
            'emp_id' => $emp_id
        );
        \AuctionCore\CarResource\Car::add_car_trace_log($car_id, $car_action_data);

        /**
         * 记录拍品跟踪日志
         */
        $order_action_data = array(
            'action_name' => $action,
            'emp_id' => $emp_id
        );
        \AuctionCore\AuctionOrder\AuOrder::add_order_trace_log($order_id, $order_action_data);
    }

	/**
	 * 通过采购单获取争议数据
	 *
	 * @param $arr 采购单数据
	 * @return mixed
	 */
	public static function getDisputeByPurchaseOrder($arr){
        	return self::getDisputeCountByCondition($arr);
    }

	/**
	 * 根据条件获取争议数据
	 *
	 * @param $condition
	 * @return mixed
	 */
	private static function getDisputeCountByCondition($condition){
		return M('dispute')->where($condition)->count();
	}

}
